<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>书签</title>
  <style>
    #top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 3px 7px;
    }

    #out {
      display: block;
      background: #e56464;
      width: 55px;
      height: 26px;
      line-height: 26px;
      text-align: center;
      border-radius: 22px;
      color: white;
    }

    #tip,
    #fileName {
      display: inline;
    }

    .tip {
      background: #959595;
      color: wheat;
      padding: 5px;
      margin: 0;
      margin-bottom: 2px;
      word-break: break-all;
      min-height: 22px;
    }

    .folder {
      background: #e5e3ca;
      display: flex;
      padding: 12px 8px;
      align-items: center;
      color: black;
      font-size: 18px;
      border-bottom: 1px solid #f3f2f1;
      position: relative;
    }

    .link {
      /* background: #91d8d3; */
      display: flex;
      padding: 12px 8px;
      align-items: center;
      justify-content: space-between;
      color: black;
      font-size: 18px;
      border-bottom: 1px solid #bebebe;
      position: relative;
    }

    .zz {
      position: absolute;
      width: 100%;
      height: 100%;
      left: 0;
      z-index: 9;
    }

    .txt {
      text-align: left;
      width: 100%;
    }

    .img {
      max-width: 26px;
      margin-right: 10px;
      width: 26px;
      height: 26px;
    }

    #refresh {
      /* position: fixed;
      top: 12px;
      right: 20px; */
      width: 40px;
      height: 40px;
      background-color: antiquewhite;
      z-index: 9999;
      border-radius: 12px;
      font-size: 30px;
      cursor: pointer;
    }

    .copy {
      right: 0;
      background-color: #8d8a71;
      padding: 2px 5px;
      font-size: 16px;
      opacity: 0.6;
      color: white;
      border-radius: 17px;
      z-index: 99;
      min-width: 33px;
    }

    .copy2 {
      background-color: #33b6d2;
    }
  </style>
</head>

<body style="background: #e9e9e9; margin: 0; padding: 0; position: relative;">

  <div id="top">
    <div id="out" onclick="outFn()">退出</div>
    <div class="search_content">
      <input id="search" placeholder="搜索，多条件的话使用空格隔开"></input>
      <button id="search_yes" onclick="search_yes_fun()">√</button>
      <button id="search_clear" onclick="search_clear_fun()">x</button>
    </div>
    <div id="refresh" onclick="refreshFn()">🚶‍♂️</div>
  </div>

  <div class="tip">
    <div id="fileName"></div>/<div id="tip"></div>
  </div>

  <div id="folderDir" onclick="folderFn(event)">
    <!-- <div class="folder">
      <img class="img" src="../images/folder.svg">
      <div>视频1</div>
    </div> -->
  </div>

  <div id="linkDir" style="margin-bottom: 70px;" onclick="openLink(event)">
    <!-- <div class="link">
      <img class="img" src="../images/链接.png">
      <div>视频3</div>
      <div class="zz"></div>
    </div> -->
  </div>
</body>

<script src='./js/giteeApi.js'></script>
<script src='./js/config.js'></script>
<script src="./js/local.js"></script>

<script>

  let bookmarks; // 保存书签原数组
  let bookmarksIdObj = {}; //  保存书签id为key的对象

  /* 获取书签文件Blob */
  function getFileContent(path, callback) {
    let than = this
    geteeApi.Repositories.contents({ path })
      .then(function ({ data }) {
        let info = JSON.parse(decodeURIComponent(atob(data['content'])))
        let send = JSON.stringify(info[0]['children'][0]["children"])
        let resp = JSON.parse(send);

        if (data.sha != db.getData('sha')) {
          db.setData('sha', data.sha);
          db.setData('bookmarks', resp)
          bookmarks = resp;
          location.reload();
        }
        callback && callback();
      })
      .catch(function (error) {
        console.log(error);
        alert('获取书签 失败了');
        location.href = '/';
      });
  }

  // 根据书签id重组成对象
  function bookmarksToObj(data = bookmarks) {
    data.forEach((item, index) => {
      if (item.children) { bookmarksIdObj[item.id] = item; bookmarksToObj(item.children) }
      else bookmarksIdObj[item.id] = item;
    })
  }

  // 根据查询关键字重组成对象，并显示列表
  function querySearchKeyValue(valueArr = []) {
    let key_name = valueArr.join('_');
    const regex = new RegExp(valueArr.map(k => `(?=.*${k})`).join(''), 'g');
    if (!bookmarksIdObj[key_name]) {
      let a = [];
      Object.keys(bookmarksIdObj).forEach(key => {
        try {
          let v = bookmarksIdObj[key];
          if (v?.title?.match(regex) || (v.url && decodeURIComponent(v.url).match(regex))) { a.push(v); }
        } catch (error) { }
      })
      bookmarksIdObj[key_name] = a;
    }
    history.pushState({}, '', `#${key_name}`);
    addBookmarks(bookmarksIdObj[key_name]);
  }
  document.getElementById('search').addEventListener('keydown', function (event) {
    if (event.key === 'Enter' || event.keyCode === 13) { search_yes_fun(); }
  });
  document.getElementById('search').addEventListener('input', function () { search_yes_fun(); });
  function search_yes_fun() {
    let value = document.getElementById('search').value;
    if (!value) return;
    let sa = [];
    value.split(' ').forEach(item => { item.trim() && sa.push(item.trim()); })
    if (sa.length > 0) querySearchKeyValue(sa);
  }
  function search_clear_fun() {
    // document.getElementById('search').value = '';
    history.back();
  }

  /* 点击文件夹事件 */
  function folderFn(event) {
    let { target } = event
    let id = target.getAttribute('data-id');

    history.pushState({}, '', `#${id}`);
    addBookmarks(bookmarksIdObj[id]);
  }

  /* 打开链接 */
  function openLink(event) { let { target } = event; let url = target.getAttribute('data-url'); url && window.open(url); }

  /* 渲染书签到页面 */
  function addBookmarks(arr = bookmarks) {
    arr.children && (arr = arr.children);
    // if (arr.length == 0) { return; }
    clear();
    arr.forEach((element, index) => {
      if (element.children) {
        var div = document.createElement("div");
        div.setAttribute('class', 'folder')
        div.setAttribute('data-title', element.title)
        div.setAttribute('data-url', element.url || '')
        div.setAttribute('data-id', element.id || '')
        div.innerHTML = ` <img class="img" src="./images/folder.svg"/> 
            <div >${element.title}</div>
            <div class="zz" data-title="${element.title}" data-url="${element.url || ""}" data-id="${element.id}"></div>`
        document.getElementById("folderDir").appendChild(div)
      } else {
        let urlArr = element.url.split('/')
        let favicon = urlArr[0] + '//' + urlArr[2] + '/favicon.ico'
        var div = document.createElement("div");
        div.setAttribute('class', 'link')
        div.setAttribute('data-title', element.title)
        div.setAttribute('data-url', element.url || '')
        div.setAttribute('data-id', element.id || '')
        div.innerHTML = ` <img class="img" src="${favicon}" /> 
            <div class="txt"  data-title="${element.title}" data-url="${element.url || ""}" data-id="${element.id}">${element.title}</div>
            <div class="copy" onclick="clickCopy(event,'${element.title}')">复制</div>`
        document.getElementById("linkDir").appendChild(div)
      }
    });
    changeTip();
  }

  /* 删除现有的选项 */
  function clear() { document.getElementById('folderDir').innerHTML = ''; document.getElementById('linkDir').innerHTML = ''; }

  // 退出到目录
  function outFn() { location.href = './index.html'; }

  // 切换刷新图片
  let refTime = 0, tt = 0;
  function refreshFn() {
    clearInterval(refTime);
    getFileContent(db.getData('filePath'), function () { clearInterval(refTime); });
    refTime = setInterval(() => { document.getElementById('refresh').innerHTML = tt++ % 2 == 1 ? '🏃‍♂️' : '🚶‍♂️'; }, 200);
  }

  // 保存标题碎屑
  function changeTip() {
    let tips = [];
    let hash = decodeURIComponent(location.hash.substring(1));
    if (hash && bookmarksIdObj[hash]) { addTip(hash); }
    document.getElementById('tip').innerHTML = document.title = tips.join('/');
    function addTip(hash) {
      let d = bookmarksIdObj[hash]; d && tips.unshift(`<a href="#${d['id']}">${d['title'] || '搜索：' + hash}</a>`);
      bookmarksIdObj[d['parentId']] && addTip(d['parentId'])
    }
  }

  // 点击复制文本
  function clickCopy(event, text) {
    event.target.classList.add('copy2'); setTimeout(() => { event.target.classList.remove('copy2') }, 700); copyText(text);
  }

  // 复制文本内容
  function copyText(text) {
    let inputDom = document.createElement('input');  // 创建一个input元素
    // let inputDom = document.createElement('textarea');  // 创建一个input元素
    inputDom.setAttribute('readonly', 'readonly'); // 防止手机上弹出软键盘
    inputDom.value = text; // 给input元素赋值
    document.body.appendChild(inputDom); // 添加到body
    inputDom.select(); //选中input元素的内容
    document.execCommand('Copy'); // 执行浏览器复制命令
    inputDom.style.display = 'none';
    inputDom.remove(); // 移除input元素
  }

  // 监听浏览器返回事件
  window.addEventListener('popstate', function (e) { addBookmarks(bookmarksIdObj[decodeURIComponent(location.hash.substring(1))]); });

  // 启动
  function run() {
    document.getElementById('fileName').innerHTML = `<a href="#">${db.getData('fileName')}</a>`;
    bookmarks = db.getData('bookmarks') || [];
    bookmarksToObj();

    let hash = location.hash.substring(1);
    addBookmarks(bookmarksIdObj[hash]);

    refreshFn(); // 重新获取最新书签
  }
  run();

</script>

</html>